#include "Logger.h"
#include <time.h>

std::ofstream* Logger::ofs = NULL;
int Logger::reportingLevel = logDEBUG;
std::string* Logger::levelNames = NULL;

int& Logger::ReportingLevel()
{
	return reportingLevel;
}

void Logger::init(int repLevel, std::string filename)
{
	if(levelNames == NULL)
	{
		levelNames = new std::string[NUM_LOG_LEVELS];

		levelNames[0] = "ERROR";
		levelNames[1] = "WARNING";
		levelNames[2] = "INFO";
		levelNames[3] = "DEBUG";
		levelNames[4] = "DEBUG1";
		levelNames[5] = "DEBUG2";
		levelNames[6] = "DEBUG3";
		levelNames[7] = "DEBUG4";
	}

	reportingLevel = repLevel;

	if(ofs != NULL)
	{
		ofs->close();
		delete ofs;
		ofs = NULL;
	}

	ofs = new std::ofstream;
	ofs->open(filename.c_str());
}

void Logger::shutdown()
{
	ofs->close();
	ofs = NULL;
}

void printCurrentTime(std::ostringstream& dest)
{
	time_t rawtime;
	struct tm * timeinfo;

	time ( &rawtime );
	timeinfo = localtime ( &rawtime );

	static char timeBuf[256];

	// time format:
	// mm/dd/yyyy hh:mm:ss
	sprintf(timeBuf, "%02d/%02d/%04d %02d:%02d:%02d", timeinfo->tm_mon, timeinfo->tm_mday, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); 

	dest << timeBuf;
}

std::ostringstream& Logger::Get(int level)
{
	//std::cout << "Entered logger get at level " << level <<  "\n";
	//time_t rawtime;
	//time ( &rawtime );
	//os << ctime(&rawtime);
	printCurrentTime(os);
	//std::cout << "A\n";
	os << " " << levelNames[level] << ": ";
	//std::cout << "B\n";
	os << std::string(level > logDEBUG ? level - logDEBUG : 0, '\t');
	//std::cout << "D\n";
	messageLevel = level;
	//std::cout << "About to leave logger get...\n";
	return os;
}

Logger::Logger()
{
}

Logger::~Logger()
{
   os << std::endl;
   (*ofs) << os.str();
   ofs->flush();

   if(messageLevel < logDEBUG)
	   std::cout << os.str();
}
